package com.ljm.boot.rocketmq.transaction;

import com.ljm.boot.rocketmq.domain.OrderInfo;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.messaging.Message;

import java.util.Optional;

@RocketMQTransactionListener
public class OrderTransaction implements RocketMQLocalTransactionListener {
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        String transId = (String) message.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        System.out.printf("#### executeLocalTransaction  transactionId=%s %n",
                transId);
        //执行本地事务，并记录日志
        //ordersService.save((Orders) 0);
        //执行成功，可以提交事务
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String transId = (String) message.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        System.out.printf("#### checkLocalTransaction transactionId=%s %n", transId);
        OrderInfo orderInfo = new OrderInfo();
        Optional<OrderInfo> optional = Optional.of(orderInfo);
        if (optional.isPresent()) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
